package com.nic.view.widget;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.nic.view.R;
import com.nic.view.adapter.CommonCheckAdapter;
import com.nic.view.model.CommonChooseBean;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 层级复合单选列表 省市区
 * Created by Administrator on 2018/8/1.
 */

public class SpecialLevelPopWindow extends CommonPopupWindow implements View.OnClickListener {
    public final static int TYPE_SINGLE = 0;//单选
    public final static int TYPE_MULTI = 1;//多选
    private TextView tv_shadow;
    private Button bt_cancel;
    private Button bt_confirm;
    private LinearLayout llContent;
    private Map<Integer, Map<String, String>> checkedMap = new TreeMap<>(new MapKeyComparator());
    private int selectType;
    private boolean isClear = true;

    public SpecialLevelPopWindow(Context c, int selectType) {
        super(c, R.layout.pop_single_special, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        this.selectType = selectType;
        init();
    }


    public void init() {

        llContent = (LinearLayout) contentView.findViewById(R.id.ll_content);
        tv_shadow = (TextView) contentView.findViewById(R.id.tv_shadow);
        tv_shadow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPopupWindow().dismiss();
            }
        });
        bt_cancel = (Button) contentView.findViewById(R.id.cancel);
        bt_cancel.setOnClickListener(this);
        bt_confirm = (Button) contentView.findViewById(R.id.confirm);
        bt_confirm.setOnClickListener(this);
        // 设置弹出窗体需要软键盘，
        getPopupWindow().setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        // 再设置模式，和Activity的一样，覆盖，调整大小。
        getPopupWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    /**
     * 是否禁用确认按钮
     *
     * @param enable
     */
    public void setConfirmEnable(boolean enable) {
        bt_confirm.setEnabled(enable);
    }

    /**
     * 是否清除子项view
     */
    public void setClearChildView(boolean isClear) {
        this.isClear = isClear;
    }

    public void addItemContent(String subTitle, List<CommonChooseBean> list, final OnItemClickListener mOnItemClickListener) {
        final MultSpecialView multSpecialView = new MultSpecialView(context, selectType);
        multSpecialView.setSubTitle(subTitle);
        if (TYPE_SINGLE == selectType) {
            multSpecialView.setSingleList(list);
            multSpecialView.setSingleListener(new CommonCheckAdapter.OnClickItemSingleListener() {
                @Override
                public void onItemClick(int position) {
                    try {
                        CommonChooseBean ccb = multSpecialView.getAdapter().getList().get(position);
                        Map<String, String> map = new HashMap<String, String>();
                        map.put(ccb.getId(), ccb.getName());
                        remove(multSpecialView, map);
                        if (mOnItemClickListener != null) {
                            mOnItemClickListener.onItemClick(map);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            multSpecialView.setMutiList(list);
            multSpecialView.setMultiListener(new CommonCheckAdapter.OnClickItemMultiListener() {
                @Override
                public void checkedItem(Map<String, String> map) {
                    remove(multSpecialView, map);
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(map);
                    }
                }
            });
        }

        llContent.addView(multSpecialView);
    }

    private void remove(MultSpecialView multSpecialView, Map<String, String> map) {
        try {
            int position = 0;
            for (int i = 0; i < llContent.getChildCount(); i++) {
                if (llContent.getChildAt(i) == multSpecialView) {
                    checkedMap.put(i, map);
                    position = i;
                }
            }
            if (isClear) {
                int count = llContent.getChildCount();
                if (count > position + 1) {
                    for (int i = position + 1; i < count; i++) {
                        llContent.removeViewAt(position + 1);
                        checkedMap.remove(i);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String[] getCheckedData() {
        String str[] = new String[2];
        List<String> idList = new ArrayList<>();
        List<String> nameList = new ArrayList<>();
        for (Map.Entry<Integer, Map<String, String>> beanEntry : checkedMap.entrySet()) {
            for (Map.Entry<String, String> map : beanEntry.getValue().entrySet()) {
                idList.add(map.getKey());
                nameList.add(map.getValue());
            }
        }
        str[0] = TextUtils.join(",", idList);
        str[1] = TextUtils.join("-", nameList);
        return str;
    }

    private OnConfirmListener onConfirmListener;

    public void setOnConfirmListener(OnConfirmListener onConfirmListener) {
        this.onConfirmListener = onConfirmListener;
    }


    class MapKeyComparator implements Comparator<Integer> {

        @Override
        public int compare(Integer int1, Integer int2) {

            return int1.compareTo(int2);
        }
    }


    public void showAsDropDown(View view) {
        if (!getPopupWindow().isShowing() && !((Activity) context).isFinishing()) {

            getPopupWindow().showAsDropDown(view);
        }
    }

    public boolean isShow() {
        return getPopupWindow().isShowing();
    }

    public void showAtLocation(View view) {
        if (!getPopupWindow().isShowing() && !((Activity) context).isFinishing()) {
            getPopupWindow().showAtLocation(view, Gravity.CENTER, 0, 0);
        }
    }

    public void show() {
        if (!getPopupWindow().isShowing() && !((Activity) context).isFinishing()) {
            getPopupWindow().showAtLocation(((Activity) context).getWindow().getDecorView(), Gravity.CENTER, 0, 0);
        }
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.cancel) {
            getPopupWindow().dismiss();
            checkedMap.clear();
//            llContent.removeAllViewsInLayout();
        } else if (i == R.id.confirm) {
            getPopupWindow().dismiss();
            if (onConfirmListener != null) {
                onConfirmListener.onConfirm(getCheckedData());
            }
        }
    }

    public void removeChildViews() {
        llContent.removeAllViewsInLayout();
    }


    public void OnDismissListener(PopupWindow.OnDismissListener listener) {
        getPopupWindow().setOnDismissListener(listener);
    }


//    /**
//     * 区域查询字典
//     *
//     * @param id
//     */
//    public void getArea(String id) {
//        AreaReq req = new AreaReq();
//        String sessionId = (String) SPUtils.get(act, "sessionId", "");
//        req.token = sessionId;
//        req.id = "" + id;
//        HttpManager.getInstance().getAreaTree(req, new HttpResponseListener<AreaListResp>(act) {
//            @Override
//            public void onError(Call call, Exception e, int id) {
//                super.onError(call, e, id);
//            }
//
//            @Override
//            public void onResponse(BaseResponse<AreaListResp> response, int id) {
//                super.onResponse(response, id);
//                if (response == null || response.getData() == null || response.getData().rows == null || response.getData().rows.isEmpty())
//                    return;
//                List<CommonChooseBean> chooselist = new ArrayList<CommonChooseBean>();
//                for (AreaListResp.ListBean row : response.getData().rows) {
//                    CommonChooseBean bean = new CommonChooseBean();
//                    bean.setId(row.areaId);
//                    bean.setName(row.areaName);
//                    chooselist.add(bean);
//                }
//                addItemContent("区域选择", chooselist, new OnItemClickListener() {
//                    @Override
//                    public void onItemClick(CommonChooseBean ccb) {
//                        getArea(ccb.getId());
//                    }
//                });
//
//            }
//        });
//    }
//

    public interface OnItemClickListener {
        /**
         * id,value
         *
         * @param map
         */
        void onItemClick(Map<String, String> map);
    }

    public interface OnConfirmListener {
        /**
         * ids,values
         */
        void onConfirm(String[] str);
    }
}
